from decimal import Decimal

from django.shortcuts import render

# Create your views here.
from rest_framework.generics import CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from django_redis import get_redis_connection

from goods.models import SKU
from orders import serializers
from orders.serializers import OrderCreateSerializer


class OrderListView(APIView):
	"""
	将reids数据库中的购物车信息取出，筛选选中的商品，返回订单信息字典
	"""
	permission_classes = [IsAuthenticated]

	def get(self, request):
		user = request.user
		conn = get_redis_connection('cart')
		reids_count_dict = conn.hgetall('cart_%s' % user.id)                # type:dict
		redis_selected_set = conn.smembers('cart_selected_%s' % user.id)

		skus_dict = {}
		for sku_id, count in reids_count_dict.items():
			if sku_id in redis_selected_set:
				skus_dict[int(sku_id)] = int(count)

		skus = SKU.objects.filter(id__in=skus_dict.keys())
		for sku in skus:
			sku.count = skus_dict[sku.id]
			# print(sku.name)

		data = {'freight':Decimal(10.00), 'skus':skus }
		data_serializer = serializers.OrderListSerializer(data)

		return  Response(data_serializer.data)


class OrderCreateView(CreateAPIView):

	permission_classes = [IsAuthenticated]
	serializer_class = OrderCreateSerializer